﻿Imports SpatialAlbum.Core.Database

Public Class DatabaseStatistics

    Private m_stats As Dictionary(Of String, Object) = Nothing
    Private m_connection As Connection = Nothing

    Public Property Count(ByVal table As String) As Integer
        Get
            Dim key As String = table & "Count"
            If m_stats.ContainsKey(key) Then
                Return CType(m_stats.Item(key), Integer)
            Else
                Count(table) = GetCount(table, m_connection)
                Return -1
            End If
        End Get
        Set(ByVal value As Integer)
            Dim key As String = table & "Count"
            m_stats.Item(key) = value
        End Set
    End Property

    Private Sub New(ByVal connection As Connection)
        m_stats = New Dictionary(Of String, Object)
        m_connection = connection
    End Sub

    Public Sub Refresh()
        For Each table As String In Database.TableNames
            Count(table) = GetCount(table, m_connection)
        Next
    End Sub

    Public Sub Refresh(ByVal table As String)
        If Database.TableNames.Contains(table) Then Count(table) = GetCount(table, m_connection)
    End Sub

    Private Sub New()
    End Sub

    Public Shared Function GetStatistics(ByVal connection As Connection) As DatabaseStatistics
        Dim stats As New DatabaseStatistics(connection)
        stats.Refresh()
        Return stats
    End Function

    Private Shared Function GetCount(ByVal table As String, ByVal connection As Connection, Optional ByVal where As String = "") As Integer
        Dim cmd As SqlCommand = connection.CreateCommand()
        cmd.CommandText = "SELECT COUNT(*) FROM dbo." & table
        If where <> "" Then cmd.CommandText &= " WHERE " & where
        ReportSqlCommand("get count", cmd)
        Try
            Dim n As Integer = CType(cmd.ExecuteScalar(), Integer)
            Return n
        Catch ex As Exception
            ReportException(ex)
            Return -1
        End Try
    End Function
End Class
